<template>
  <!-- 注册表单组件 -->
  <a-form-model
    id="register"
    ref="ruleForm"
    :model="formData"
    :rules="rules"
    class="register-form animate__animated animate__fadeIn"
    @submit="handleSubmit"
  >
    <a-form-model-item prop="phone">
      <a-input v-model="formData.phone" placeholder="请输入手机号">
        <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
      </a-input>
    </a-form-model-item>
    <a-form-model-item prop="password">
      <a-input-password v-model="formData.password" placeholder="请输入密码">
        <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
      </a-input-password>
    </a-form-model-item>
    <a-form-model-item>
      <a-button type="primary" html-type="submit" class="register-form-button">
        注册
      </a-button>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import md5 from "js-md5";
import requests from "../js/requests.js";
import { Input, Icon, Button, FormModel } from "ant-design-vue";
export default {
  name: "Register",
  components: {
    AInput: Input,
    AInputPassword: Input.Password,
    AIcon: Icon,
    AButton: Button,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
  },
  data() {
    return {
      formData: {
        phone: "",
        password: "",
      },
      rules: {
        phone: [
        { required: true, message: "请输入手机号！", trigger: "change" },
        { max: 32, message: "长度不能超过32个字符！" ,trigger: "change"},
        { pattern: new RegExp("^[^\\s]*$"), message: "不能包含空格" ,trigger: "change"},
      ],
      password: [
        { required: true, message: "请输入密码！" },
        { max: 100, message: "长度不能超过100个字符！" },
      ],
      },
      
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.$refs.ruleForm.validate((valid) => {
        if(valid) {
          let user = new Object();
          user.phone = this.formData.phone;
          user.password = md5(this.formData.password);
          // 发送数据到后端注册账号
          requests.registerUser(user).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.$emit("toLogin");
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      })
    },
  },
};
</script>

<style scoped>
#register .register-form {
  max-width: 300px;
}

#register .register-form-button {
  width: 100%;
}
</style>
